<template>
  <div>
    <div class="alert">
      <div class="alert-container" v-for="item in alerts" :key="item.id">
        <div class="alert-content">{{item.content}}</div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'notice',
  data() {
    return {
      alerts: []
    }
  },
  created() {
    //组件创在完成后， id自增控制
    //id放在this对象上，并不是响应式的
    this.id = 0;

  },
  methods: {
    add(options) { //实例方法，创建一个新的alert
      const id = 'id_'+(this.id++);
      //将用户传进来的options属性展开，并合并id
      const _alert = { ...options, id: id};
      this.alerts.push(_alert);

      //自动关闭
      const duration = options.duration || 1; //单位秒
      setTimeout( () => {
        this.del(id)
      }, duration*1000)
    },
    del(id) { //删除消息
      for (let i = 0; i < this.alerts.length; i++) {
        const element = this.alerts[i];
        if (element.id === id) {
          this.alerts.splice(i,1);
          return false;
        } 
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.alert {
  position: fixed;
  width: 100%;
  top: 30px;
  left: 0;
  text-align: center;
  .alert-content {
    display: inline-block;
    padding: 8px;
    background: #fff;
    margin: 10px;
  }
}
</style>